<?php

use service\DataService;
use service\FileService;
use service\NodeService;
use service\SoapService;
use app\comm\service\SrotGoodServices;
use think\Db;
use Wechat\Loader;

/**
 * 打印输出数据到文件
 * @param mixed $data
 * @param bool $replace
 * @param string|null $pathname
 */
function p($data, $replace = false, $pathname = null)
{
    is_null($pathname) && $pathname = RUNTIME_PATH . date('Ymd') . '.txt';
    $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . "\n";
    $replace ? file_put_contents($pathname, $str) : file_put_contents($pathname, $str, FILE_APPEND);
}

/**
 * 获取mongoDB连接
 * @param string $col 数据库集合
 * @param bool $force 是否强制连接
 * @return \think\db\Query|\think\mongo\Query
 */
function mongo($col, $force = false)
{
    return Db::connect(config('mongo'), $force)->name($col);
}

/**
 * 获取微信操作对象
 * @param string $type
 * @return \Wechat\WechatMedia|\Wechat\WechatMenu|\Wechat\WechatOauth|\Wechat\WechatPay|\Wechat\WechatReceive|\Wechat\WechatScript|\Wechat\WechatUser|\Wechat\WechatExtends|\Wechat\WechatMessage
 * @throws Exception
 */
function & load_wechat($type = '')
{
    static $wechat = [];
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        $config = [
            'token' => sysconf('wechat_token'),
            'appid' => sysconf('wechat_appid'),
            'appsecret' => sysconf('wechat_appsecret'),
            'encodingaeskey' => sysconf('wechat_encodingaeskey'),
            'mch_id' => sysconf('wechat_mch_id'),
            'partnerkey' => sysconf('wechat_partnerkey'),
            'ssl_cer' => sysconf('wechat_cert_cert'),
            'ssl_key' => sysconf('wechat_cert_key'),
            'cachepath' => CACHE_PATH . 'wxpay' . DS,
        ];

        $wechat[$index] = Loader::get($type, $config);
    }
    return $wechat[$index];
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}

/**
 * 网络图片本地化
 * @param string $url
 * @return string
 */
function local_image($url)
{
    if (is_array(($result = FileService::download($url)))) {
        return $result['url'];
    }
    return $url;
}

/**
 * 日期格式化
 * @param string $date 标准日期格式
 * @param string $format 输出格式化date
 * @return false|string
 */
function format_datetime($date, $format = 'Y年m月d日 H:i:s')
{
    return empty($date) ? '' : date($format, strtotime($date));
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        return DataService::save('SystemConfig', $data, 'name');
    }
    if (empty($config)) {
        $config = Db::name('SystemConfig')->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * array_column 函数兼容
 */
if (!function_exists("array_column")) {

    function array_column(array &$rows, $column_key, $index_key = null)
    {
        $data = [];
        foreach ($rows as $row) {
            if (empty($index_key)) {
                $data[] = $row[$column_key];
            } else {
                $data[$row[$index_key]] = $row[$column_key];
            }
        }
        return $data;
    }

}

function dd($i = '')
{
    echo "<pre>";
    print_r($i);
    echo "</pre>";
}


/**
 * 生成唯一的订单号
 * @return string
 */
function build_order_no()
{
    return date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * d笛卡尔积
 * @param $arr
 * @return array|mixed
 */
function dikaer($arr)
{
    $arr1 = array();
    $result = array_shift($arr);
    while ($arr2 = array_shift($arr)) {
        $arr1 = $result;
        $result = array();
        foreach ($arr1 as $v) {
            foreach ($arr2 as $v2) {
                $result[] = $v . ',' . $v2;
            }
        }
    }
    return $result;
}


function dikaerr($arr)
{
    $arr1 = array();
    $result = array_shift($arr);
    while ($arr2 = array_shift($arr)) {
        $arr1 = $result;
        $result = array();
        foreach ($arr1 as $v) {
            foreach ($arr2 as $v2) {
                if (!is_array($v)) $v = array($v);
                if (!is_array($v2)) $v2 = array($v2);
                $result[] = array_merge_recursive($v, $v2);
            }
        }
    }
    return $result;
}


/**
 * @name php获取中文字符拼音首字母
 * @param $str
 * @return null|string
 */
function getFirstCharter($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';
    return null;
}

/**
 * 判断是否是微信 浏览器
 * @return boolean [description]
 */
function is_weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * 判断是否是电脑，还是手机
 * @return boolean [description]
 */
function is_mobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

//获取两个日期之间所有的日期
function prDates($start, $end, $type)
{
    $dt_start = strtotime($start);
    $dt_end = strtotime($end);
    while ($dt_start <= $dt_end) {
        if ($type == 'day')
            $date[] = date('Y-m-d', $dt_start);
        if ($type == 'month')
            $date[] = date('Y-m', $dt_start);
        $dt_start = strtotime('+1 ' . $type, $dt_start);
    }
    return $date;
}


//异步请求
function post($host, $path, $port, $data) {
    $post = http_build_query($data);
    $len = strlen($post);

    $fp = fsockopen($host, $port, $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)\n";

        return;
    }

    $out = "POST $path HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Content-type: application/x-www-form-urlencoded\r\n";
    $out .= "Connection: Close\r\n";
    $out .= "Content-Length: $len\r\n";
    $out .= "\r\n";
    $out .= $post . "\r\n";
    // echo($out);
    fwrite($fp, $out);

    // 注释掉如下代码实现不等待 HTTP 响应，从而实现“异步”
//    $receive = '';
//    while (!feof($fp)) {
//        $receive .= fgets($fp, 128);
//    }
//    echo "<br />" . $receive;

    fclose($fp);
}


/**
 * @Author lignyun
 * @param $rule  积分规则
 * @param $point 会员的积分
 * @Desc    返回会员目前的等级
 * 主要用于积分变更时返回会员变更积分后的等级规则id
 */
function userLevel($rule,$point){
    foreach($rule as $k => $v){
        if($point < $v['score']){
            return $v['id'];
        }
    }
    $last = end($rule);     //数组最后的一个元素
    return $last['id'];     //返回最后的数组
}

/**
 * @Author  lingyun
 * @Desc    获取会员的当前等级信息
 * @param $point    会员当前的等级
 * @return array    $title:会员当前的等级、top_level_score:顶级积分
 */
function get_user_level($point){
    $level = db('sys_level')->order('score asc')->select();
    $last = end($level);        //最后的一个数组
//    foreach($level as $k => $v){
//        if($point < $v['score']){
//            return ['title'=>$v['title'],'logo'=>$v['logo'],'top_level_score'=>$last['score']];
//        }
//    }
//    return ['title'=>$v['title'],'logo'=>$v['logo'],'top_level_score'=>$last['score']];
    $level = db('sys_level')->where('id',$point)->find();
    return ['title'=>$level['title'],'logo'=>$level['logo'],'top_level_score'=>$level['score']];
}

/**
 * @Author  lingyun
 * @Desc    检测输入的收货地址是否正确
 * @param $address  收货地址
 * @return array    结果
 */
function check_address($address){
    //腾讯地图地址API
    $url='http://apis.map.qq.com/ws/geocoder/v1/?address='.$address.'&key=SCIBZ-DHYCX-RQZ4A-ZZB2V-2VHPH-N4FUM';
    if($result=file_get_contents($url)){
        $result = json_decode($result,true);
        if($result['status'] == 0){
            //输入地址错误
            if(($result['result']['title'] == $result['result']['address_components']['district']) || ($result['result']['address_components']['street'] == '') || ($result['result']['address_components']['street_number'] == '')){
                return ['code'=>0,'msg'=>'输入地址有误,请重新填写'];
//                $this->error('输入地址有误,请重新填写','');
            }else{      //输入地址正确
                $data['lng'] = $result['result']['location']['lng'];
                $data['lat'] = $result['result']['location']['lat'];
                return ['code'=>1,'msg'=>'地址输入正确','data'=>$data];
            }
        }else{
            return ['code'=>0,'msg'=>'地址输入错误，请重试！'];
//            $this->error('地址输入错误，请重试！');
        }
    }
}

/**
 * @Author lignyun
 * @Desc    下单计算运费
 * @param   $receive_location  收货地址 -- 详细地址
 * @param   $store_location   门店的id
 * @param   return[array]     code 0:收货地址有误,返回错误信息；code 1:收货地址正确，返回计算的运费
 */
function countDeliveryFee($receive_location,$store_id){
    //腾讯地图API -- key
    $key= Db::name('dic_config')->where('name','tx_key')->find();
    $url='http://apis.map.qq.com/ws/geocoder/v1/?address='.$receive_location.'&key='.$key['value'];
    if($result=file_get_contents($url)){
        $result = json_decode($result,true);
        if($result['status'] == 0){
            //输入地址错误
            if(($result['result']['title'] == $result['result']['address_components']['district']) || ($result['result']['address_components']['street'] == '') || ($result['result']['address_components']['street'] == '')){
                return ['code'=>0,'msg'=>'收货地址填写有误，请重新填写'];
            }else{      //输入地址正确
                $receive['lng'] = $result['result']['location']['lng'];     //收货地址精度
                $receive['lat'] = $result['result']['location']['lat'];     //收货地址纬度
            }
        }else{
            return ['code'=>0,'msg'=>$result['message']];
        }
    }
    //查询门店的信息 -- 获取经纬度
    $store = Db::name('store')->where('id',$store_id)->field('id,lng,lat')->find();
    $service = new SrotGoodServices();
    /**
     * 计算距离 -- 返回公里
     * @param  @app   1:计算m  2:计算km
     */
    $result = $service->getdispoint($receive['lat'], $receive['lng'], $store['lat'], $store['lng'],2);
    if(!empty($result)){
        //计算运费
        $fee = getDeliveryFee($result);
        if($fee['code'] == 0){
            return ['code'=>0,'msg'=>$fee['msg']];
        }else{
            return ['code'=>1,'msg'=>$fee['msg']];
        }
    }else{
        return ['code'=>0,'msg'=>'收货地址填写错误，请重新填写'];
    }
}

/**
 * @Author lignyun
 * @Desc    获取运费信息
 * @param   $distance   距离/公里
 * @param   return[string]   返回运费信息
 */
function getDeliveryFee($distance){
    //查询运费信息
    $data = Db::name('delivery_fee')->where('is_deleted',0)->order('distance asc')->select();
    foreach($data as $k => $v){
        if($distance < $v['distance']){
            return ['code'=>1,'msg'=>$v['price']];
            break;
        }
    }
    return ['code'=>0,'msg'=>'收货地址不在配送范围内，请重新下单！'];
}

/**
 * @Author  lignyun
 * @Desc    创建订单号
 * @param $uid
 * @return false|string     返回唯一订单号
 */
function create_order_sn($uid){
    $data = date('YmdHis',time());
    $code = sprintf("%06d", $uid);
    for($i=0;$i<6;$i++){
        $data .= rand(0,9);
    }
    $data .= $code;
    return $data;
}

/**
 * @Author  lingyun
 * @Desc    获取今天的起止时间戳
 * @return array start 开始  end  结束
 */
function get_today_time(){
    $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
    $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
    return ['start'=>$beginToday,'end'=>$endToday];
}

/**
 * @Author  lingyun
 * @Desc    根据IP地址查询所在的城市信息
 * @Desc    根据IP地址查询所在的城市信息
 * @param string $ip
 * @return bool|mixed   返回当前的城市信息
 */
function get_location_city($ip = ''){
    if(empty($ip)){
        return ['code'=>0,'msg'=>'查询失败'];
    }

//    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip='.$ip);
    $res = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);

//    if(empty($res)){ return ['code'=>0,'msg'=>'查询失败']; }
//    $jsonMatches = array();
//    preg_match('#\{.+?\}#', $res, $jsonMatches);
//    if(!isset($jsonMatches[0])){ return ['code'=>0,'msg'=>'查询失败']; }
//    $json = json_decode($jsonMatches[0], true);
//    if(isset($json['ret']) && $json['ret'] == 1){
//        $json['ip'] = $ip;
//        unset($json['ret']);
//    }else{
//        return ['code'=>0,'msg'=>'查询失败'];
//    }

    $result = json_decode($res,true);
    if($result['data']['city'] != '' ){
        return ['code'=>0,'msg'=>'查询失败'];
    }else{
        return ['code'=>1,'msg'=>$result['data']['city']];
    }
}

/**
 * @Author  lingyun
 * @Desc    获取会员的支付码 -- 条形码
 * @param $mid 会员的id
 */
function get_pay_code($mid){
    $pay_code = '5270'.sprintf("%04d", $cur_uid);         //会员支付码
//    $count = mb_strlen($mid,"UTF-8");       //计算会员id的长度
//    $num = 12-$count;
//    $data = '';
//    for($i=0;$i<$num;$i++){
//        $data .= rand(0,9);
//    }
//    return $data.$mid;       //会员的支付码
    return $pay_code;       //会员的支付码
}

/**
 * @Author  lingyun
 * @Desc    三级分销处理会员积分
 * @param $uid  会员id
 * @param $amount   订单总金额
 * @param $store_is   门店id
 * @param $order_id   订单id
 * @param $money   会员当前的与额  为空表示不更新
 */
function third_tier_distribution($uid,$amount,$store_id,$order_id,$money=0,$order_sn='',$pay_type=''){
    //变更门店余额记录
    $store = db('store')->where('id',$store_id)->find();
    $store_credit_log = [
        'store_id'=>$store['id'],
        'order_id'=>$order_id,
        'type'=>1,
        'credit'=>$amount,
        'cur_credit'=>$store['total_amount']+$amount,
        'remark'=>'销售商品收入',
        'addtime'=>time(),
        'order_type'=>1,
        'order_sn'=>$order_sn,
        'pay_type'=>$pay_type
    ];
    db('store_credit_log')->insert($store_credit_log);
    $store_credit_arr = [
        'total_amount'=>$store['total_amount']+$amount,
        'credit'=>$store['credit']+$amount
    ];
    db('store')->where('id',$store['id'])->update($store_credit_arr);
    //变更门店余额记录

    $user = db('user')->where('uid', $uid)->find();
    $point = floor($amount / 2);       //自己得分
    $point1 = floor($amount / 4);       //上级得分
    $point2 = floor($amount/8);        //上上记得分
    $rules = db('sys_level')->order('score asc')->select();

    //自己得分
    if($point>0){
//        $level = userLevel($rules,$user['level_point']+$point);     //会员当前等级
//        $arr['level_point'] = $user['level_point']+$point;
        $arr['pay_points'] = $user['pay_points']+$point;
//        $arr['level_id'] = $level;
        if(!empty($money)){
            $arr['user_money'] = $money;
        }
        db('user')->where('uid',$uid)->update($arr);
        $data = [
            'uid'=>$uid,
            'store_id'=>$store_id,
            'order_id'=>$order_id,
            'uidtype'=>4,
            'type'=>1,
            'point'=>$point,
//            'cur_levelpoint'=>$user['level_point']+$point,
            'curpoint'=>$user['pay_points']+$point,
            'type_cn'=>'消费赠送积分',
            'remark'=>'消费赠送积分',
            'addtime'=>time()
        ];
        db('user_point_log')->insert($data);
    }

    //上级得分
    if(($point1>0) && ($user['pid'] != '')){
        $invite_1 = db('user')->where('uid',$user['pid'])->find();
//        $level = userLevel($rules,$invite_1['level_point']+$point1);     //会员当前等级
//        $arr_1['level_point'] = $invite_1['level_point']+$point1;
        $arr_1['pay_points'] = $invite_1['pay_points']+$point1;
//        $arr_1['level_id'] = $level;
//        if(!empty($money)){
//            $arr_1['user_money'] = $money;
//        }
//        $arr_1['level_point'] = $invite_1['level_point']+$point1;
        //更新上级积分
        db('user')->where('uid',$invite_1['uid'])->update($arr_1);
        $data_1 = [
            'uid'=>$invite_1['uid'],
            'store_id'=>$store_id,
            'uidtype'=>4,
            'type'=>1,
            'point'=>$point1,
//            'cur_levelpoint'=>$invite_1['level_point']+$point1,
            'curpoint'=>$invite_1['pay_points']+$point1,
            'type_cn'=>'消费赠送积分',
            'remark'=>'消费赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->insert($data_1);
    }
    //上上级积分
    if(($point2>0) && ($user['t_pid'] != '')){
        $invite_2 = db('user')->where('uid',$user['t_pid'])->find();
//        $level = userLevel($rules,$invite_2['level_point']+$point2);     //会员当前等级
//        $arr_2['level_point'] = $invite_2['level_point']+$point2;
        $arr_2['pay_points'] = $invite_2['pay_points']+$point2;
//        $arr_2['level_id'] = $level;
//        if(!empty($money)){
//            $arr_2['user_money'] = $money;
//        }
        //更新上级积分
        db('user')->where('uid',$invite_2['uid'])->update($arr_2);
        $data_2 = [
            'uid'=>$invite_2['uid'],
            'store_id'=>$store_id,
            'uidtype'=>4,
            'type'=>1,
            'point'=>$point2,
//            'cur_levelpoint'=>$invite_2['level_point']+$point2,
            'curpoint'=>$invite_2['pay_points']+$point2,
            'type_cn'=>'消费赠送积分',
            'remark'=>'消费赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->insert($data_2);
    }
}

/**
 * @Author  lingyun
 * @Desc    会员充值三级分销返积分并且处理会员等级
 * 2018-03-21
 */
function recharge_third_distribution($uid,$amount){
    $rule = db('sys_point')->where('code',3)->find();       //积分规则
    $member = db('user')->where('uid',$uid)->find();         //会员自己的信息
    $level_id = user_level($amount,$member);                        //会员当前的等级
    $point = floor($amount);
    if($point>0){
        //会员自己的积分记录数据
        $data_1 = [
            'uid'=>$uid,
            'admin_id'=>0,
            'store_id'=>0,
            'order_id'=>0,
            'uidtype'=>5,
            'signid'=>3,
            'type'=>1,
            'point'=>floor($amount),
            'curpoint'=>$member['pay_points']+floor($amount),
            'type_cn'=>'充值获得积分',
            'remark'=>'充值获得积分',
            'addtime'=>time(),
            'tuijianrenuid'=>$member['pid']
        ];
        db('user_point_log')->insert($data_1);      //新增会员积分记录
        db('user')->where('uid',$uid)->setInc('pay_points',floor($amount));
        db('user')->where('uid',$uid)->update(['level_id'=>$level_id]);     //更新会员当前的等级

        //会员上级的积分记录
        if(!empty($member['pid'])){
            $p_user = db('user')->where('uid',$member['pid'])->find();      //上级领导

            $data_2 = [
                'uid'=>$member['pid'],
                'admin_id'=>0,
                'store_id'=>0,
                'order_id'=>0,
                'uidtype'=>5,
                'signid'=>3,
                'type'=>1,
                'point'=>floor($amount/2),
                'curpoint'=>$p_user['pay_points']+floor($amount/2),
                'type_cn'=>'会员充值，获得积分',
                'remark'=>'会员充值，获得积分',
                'addtime'=>time(),
                'tuijianrenuid'=>$p_user['pid']
            ];
            db('user_point_log')->insert($data_2);      //新增上级积分记录
            db('user')->where('uid',$member['pid'])->setInc('pay_points',floor($amount/2));
        }
        //会员上上级的积分记录
        if(!empty($member['t_pid'])){
            $tp_user = db('user')->where('uid',$member['t_pid'])->find();      //上级领导

            $data_2 = [
                'uid'=>$member['t_pid'],
                'admin_id'=>0,
                'store_id'=>0,
                'order_id'=>0,
                'uidtype'=>5,
                'signid'=>3,
                'type'=>1,
                'point'=>floor($amount/4),
                'curpoint'=>$tp_user['pay_points']+floor($amount/4),
                'type_cn'=>'会员充值，获得积分',
                'remark'=>'会员充值，获得积分',
                'addtime'=>time(),
                'tuijianrenuid'=>$tp_user['pid']
            ];
            db('user_point_log')->insert($data_2);      //新增上级积分记录
            db('user')->where('uid',$member['t_pid'])->setInc('pay_points',floor($amount/4));
        }
    }

}

/**
 * @Author  lingyun
 * @Desc    收银台变更积分
 * @param $uid
 * @param $amount
 * @param $store_id
 * @param $order_id
 * @param int $money
 * @param string $order_sn
 * @param string $order_leixing 订单类型，1商品订单（线上、线下），2（优惠券订单），3充值订单，0没有详情的订单记录
 */
function shouyintai_point($uid,$amount,$store_id,$order_id,$money=0,$order_sn='',$order_leixing=0){
    $user = db('user')->where('uid', $uid)->find();
    $point = floor($amount / 2);       //自己得分
    $point1 = floor($amount / 4);       //上级得分
    $point2 = floor($amount/8);        //上上记得分
    $rules = db('sys_level')->order('score asc')->select();

    //自己得分
    if($point>0){
//        $level = userLevel($rules,$user['level_point']+$point);     //会员当前等级
//        $arr['level_point'] = $user['level_point']+$point;
        $arr['pay_points'] = $user['pay_points']+$point;
//        $arr['level_id'] = $level;
        if(!empty($money)){
            $arr['user_money'] = $money;
        }
        db('user')->where('uid',$uid)->update($arr);
        $data = [
            'uid'=>$uid,
            'store_id'=>$store_id,
            'order_id'=>$order_id,
            'uidtype'=>4,
            'type'=>1,
            'point'=>$point,
//            'cur_levelpoint'=>$user['level_point']+$point,
            'curpoint'=>$user['pay_points']+$point,
            'type_cn'=>'消费赠送积分',
            'remark'=>'消费赠送积分',
            'addtime'=>time(),
            'order_type'=>$order_leixing
        ];
        db('user_point_log')->insert($data);
    }

    //上级得分
    if(($point1>0) && ($user['pid'] != '')){
        $invite_1 = db('user')->where('uid',$user['pid'])->find();
//        $level = userLevel($rules,$invite_1['level_point']+$point1);     //会员当前等级
//        $arr_1['level_point'] = $invite_1['level_point']+$point1;
        $arr_1['pay_points'] = $invite_1['pay_points']+$point1;
//        $arr_1['level_id'] = $level;
//        if(!empty($money)){
//            $arr_1['user_money'] = $money;
//        }
//        $arr_1['level_point'] = $invite_1['level_point']+$point1;
        //更新上级积分
        db('user')->where('uid',$invite_1['uid'])->update($arr_1);
        $data_1 = [
            'uid'=>$invite_1['uid'],
            'store_id'=>$store_id,
            'uidtype'=>4,
            'type'=>1,
            'point'=>$point1,
//            'cur_levelpoint'=>$invite_1['level_point']+$point1,
            'curpoint'=>$invite_1['pay_points']+$point1,
            'type_cn'=>'消费赠送积分',
            'remark'=>'消费赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->insert($data_1);
    }
    //上上级积分
    if(($point2>0) && ($user['t_pid'] != '')){
        $invite_2 = db('user')->where('uid',$user['t_pid'])->find();
//        $level = userLevel($rules,$invite_2['level_point']+$point2);     //会员当前等级
//        $arr_2['level_point'] = $invite_2['level_point']+$point2;
        $arr_2['pay_points'] = $invite_2['pay_points']+$point2;
//        $arr_2['level_id'] = $level;
//        if(!empty($money)){
//            $arr_2['user_money'] = $money;
//        }
        //更新上级积分
        db('user')->where('uid',$invite_2['uid'])->update($arr_2);
        $data_2 = [
            'uid'=>$invite_2['uid'],
            'store_id'=>$store_id,
            'uidtype'=>4,
            'type'=>1,
            'point'=>$point2,
//            'cur_levelpoint'=>$invite_2['level_point']+$point2,
            'curpoint'=>$invite_2['pay_points']+$point2,
            'type_cn'=>'消费赠送积分',
            'remark'=>'消费赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->insert($data_2);
    }
}

/**
 * @Author  lingyun
 * @Desc    会员充值等级处理
 * @param   $amount   会员充值的金额
 * 2018-03-21
 */
function user_level($amount,$member){
    $rule = db('sys_level')->order('score asc')->select();
    $count = count($rule);
    $cur_level_id = 1;
    foreach($rule as $k=>$v){
        if($amount<$v['score']){        //返回等级id
            $cur_level_id = $rule[$k-1]['id'];
            break;
        }
    }
    if($cur_level_id == 0){
        $cur_level_id = $rule[$count-1]['id'];
    }

    if($member['level_id'] > $cur_level_id){           //会员等级
        return $member['level_id'];
    }else{
        return $cur_level_id;
    }
}

/**
 * @Author  lingyun
 * @Desc    获取本月的起止时间戳
 */
function get_month_time(){
    $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
    $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));

    return ['start'=>$beginThismonth,'end'=>$endThismonth];
}